﻿#include "stdafx.h"
#include "HLuaScript.h"

CHLuaScript::CHLuaScript(void)
{
	m_LuaState = lua_open();
	lua_cpcall(m_LuaState, luaopen_base, 0);
	lua_cpcall(m_LuaState, luaopen_io, 0);
	lua_cpcall(m_LuaState, luaopen_string, 0);
	lua_cpcall(m_LuaState, luaopen_math, 0);
}

CHLuaScript::~CHLuaScript(void)
{
	lua_close(m_LuaState);
}

char* CHLuaScript::GetLuaString(CString strModule, size_t nLen) const
{
	lua_getglobal(m_LuaState, StrP(strModule));
	if (!lua_isstring(m_LuaState, -1))
	{
		return NULL;
	}
	char *str = NULL;
	str = (char*)lua_tolstring(m_LuaState, -1, &nLen);
	return str;
}

int CHLuaScript::GetLuaNumber(CString strModule) const
{
	lua_getglobal(m_LuaState, StrP(strModule));
	if (!lua_isnumber(m_LuaState, -1))
	{
		return NULL;
	}
	int nTemp = 0;
	nTemp = (int)lua_tonumber(m_LuaState, -1);
	return nTemp;
}

int CHLuaScript::GetLuaFunction(CString strFunction, int *nParam, BYTE byParamSize, BYTE byReturn)
{
	ASSERT(nParam != NULL);
	ASSERT(byParamSize>0);
	ASSERT(byReturn>0);

	lua_getglobal(m_LuaState, StrP(strFunction));//lua中函数名称
	for (int i = 0; i < byParamSize; ++i)
	{
		lua_pushnumber(m_LuaState, nParam[i]);//lua压入参数
	}
	lua_call(m_LuaState, byParamSize, byReturn);//调用函数，nSize个参数，byReturn个返回值
	int nResult = 0;
	nResult = (int)lua_tonumber(m_LuaState, -1);//得到结果
	lua_pop(m_LuaState, 1);//把返回值清掉(lua的返回值)
	return nResult;
}

BOOL CHLuaScript::InitLuaScript(CString strFile)
{
	if (strFile.IsEmpty())
		return FALSE;
	
	if (luaL_loadfile(m_LuaState,StrP( strFile)) ||
		lua_pcall(m_LuaState, 0, 0, 0))
	{
		return FALSE;
	}
	return TRUE;
}